<template>
  <div class="tree-list indicator-tree">
    <div class="tree-list-top">
      <el-input
        v-model="filterText"
        placeholder="请输入名称搜索"
        clearable
        size="mini"
        prefix-icon="el-icon-search"
      />
      <el-button v-if="editable" style="margin-left: 10px;" size="mini" type="primary" plain @click="addTree">新增</el-button>
    </div>

    <div class="tree-list-main">
      <el-tree
        :data="treeData"
        :props="defaultProps"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        ref="tree"
        node-key="id"
        default-expand-all
        highlight-current
        :draggable="editable"
        @node-click="handleNodeClick"
        @node-drop="handleNodeDrop"
      >
             <span class="custom-tree-node" slot-scope="{ node, data }">
               <span>{{ node.label }}</span>
                <span v-if="editable">
                 <el-button size="mini" type="text" @click="addTree(data)">添加</el-button>
                 <el-button size="mini" type="text" @click="editTree(data)">编辑</el-button>
                 <el-button size="mini" type="text" @click="removeTree(data)">删除</el-button>
               </span>
             </span>
      </el-tree>
    </div>

    <!-- 弹窗 -->
    <simple-dialog v-bind.sync="dialog" @on-ok="onDialogOk"/>
  </div>
</template>
<script>

import dialogMixin from "@/components/common/dialog/dialog-mixin"
import treeEdit from './tree-edit'

export default {
  name: 'tree-list',
  mixins: [dialogMixin],
  components: {
  },
  props: {
    listFn: Function,
    saveFn: Function,
    batchFn: Function,
    deleteFn: Function,
    label: {
      type: String,
      default: '分类'
    },
    title: {
      type: String,
      default: '分类'
    },

    editable: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      treeLoading: false,
      filterText: '',
      treeData: [],
      list: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  methods: {
    init() {
      this.reload()
    },
    async reload() {
      if(!this.listFn) return
      const list = await this.listFn()
      this.treeData = this.handleTree(list, 'id', 'pid')
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    handleNodeClick(data) {
      if(data.id === this.currentId) {
        this.currentId = ''
        this.$refs.tree.store.currentNode.isCurrent = false
      } else {
        this.currentId = data.id
      }

      this.$emit('tree-select', this.currentId, data)
    },
    handleNodeDrop(draggingNode, dropNode, dropType, ev) {
    // 进入到某个分组内部，设置父id为drop.id，并保存当前分组
      let nodes = []
      if(dropType === 'inner') {
        draggingNode.data.pid = dropNode.data.id
        nodes = dropNode.childNodes
      } else {
        // 拖拽到某个节点的前后，设置父id为drop.pid
        draggingNode.data.pid = dropNode.data.pid
        nodes = dropNode.parent.childNodes
      }

      const params = []
      nodes.forEach((node, idx) => {
        const data = node.data
        const {id, pid} = data

        params.push({
          id, pid, px: idx + 1
        })
      })

      this.treeLoading = true
      this.batchFn(params).then(_ => {
        this.treeLoading = false
        this.$notify.success('操作成功!')
      }).catch(e => {
        console.error(e)
        this.treeLoading = false
      })

    },
    addTree(data) {
      let pid = null
      if(data && data.id) {
        pid = data.id
      }
      this.setDialog({
        comp: treeEdit,
        width: '500px',
        height: '400px',
        title: '新增' + this.title,
        props: {
          treeData: this.treeData,
          pid,
          saveFn: this.saveFn,
          label: this.label
        }
      })
    },
    editTree(data) {
      this.setDialog({
        comp: treeEdit,
        width: '500px',
        height: '400px',
        title: '编辑' + this.title,
        props: {
          treeData: this.treeData,
          pid: data.pid,
          id: data.id,
          name: data.name,
          saveFn: this.saveFn,
          label: this.label
        }
      })
    },
    removeTree(data) {
      this.$modal.confirm('确定删除该节点?').then(_ => {
        this.deleteFn({id: data.id}).then(res => {
          if(res.code === -1) {
            this.$modal.alertError(res.msg)
            return
          }
          this.reload()
        })
      })
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    this.init()
  }
}
</script>
<style scoped lang="scss">
.tree-list {
  box-sizing: border-box;
  padding: 10px;
  height: 100%;

  &-top {
    display: flex;
  }

  &-main {
    height: calc(100% - 42px);
    margin-top: 10px;
    overflow-y: auto;
  }

  .custom-tree-node {
    display: flex;
    justify-content: space-between;
    flex: 1;
    align-items: center;
    font-size: 14px;
    padding-right: 8px;
  }


}
</style>
